package com.csw.android.ffmpegtest.ui.section9

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.opengl.GLSurfaceView
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.csw.android.dev_utils.utils.ToastUtils
import com.csw.android.ffmpegtest.R
import com.csw.android.ffmpegtest.app.MyApplication
import com.csw.android.ffmpegtest.databinding.LayoutSection801Binding
import com.csw.android.ffmpegtest.gl.Section903Renderer
import com.csw.android.ffmpegtest.ui.base.DataBindingFragment
import java.io.File

/**
 * 实现ffmpeg播放本地mp4（h264\aac）视频
 */
class Section903 : DataBindingFragment<LayoutSection801Binding>() {

    private var renderer: Section903Renderer? = null
    private var allFileManageRequestTask: ActivityResultLauncher<Intent>? = null
    private var readFilePermissionTask: ActivityResultLauncher<String>? = null

    override fun getContentViewID(): Int {
        return R.layout.layout_section_801
    }

    override fun initView(rootView: View, savedInstanceState: Bundle?) {
        super.initView(rootView, savedInstanceState)
        allFileManageRequestTask = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                requirePermission()
            } else {
                ToastUtils.showShort("未授予所有文件访问权限可能无法读取视频")
                requirePermission()
            }
        }
        readFilePermissionTask = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) {
            if (it == true) {
                rootView.postDelayed({
                    val path = "/storage/emulated/0/douyin2.mp4"
//                    val path =
//                        "/storage/emulated/0/bilibili/download/34741835/c_60857337/64/video.m4s"
                    val file = File(path)
                    if (file.exists()) {
                        renderer?.playVideo(path)
                    }
                },3000)
            } else {
                ToastUtils.showShort("没有权限读取sd卡文件")
            }
        }
        dataBinding?.glSurfaceView?.run {
            setEGLContextClientVersion(3)
            setRenderer(Section903Renderer().apply {
                renderer = this
            })
            //以定时刷新的模式渲染最新的一帧
            renderMode = GLSurfaceView.RENDERMODE_CONTINUOUSLY
        }
    }

    override fun initData() {
        super.initData()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                requirePermission()
            } else {
                allFileManageRequestTask?.launch(
                    Intent(
                        Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                        Uri.parse("package:${MyApplication.instance.packageName}")
                    )
                )
            }
        } else {
            requirePermission()
        }
    }

    private fun requirePermission() {
        readFilePermissionTask?.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    override fun onResume() {
        super.onResume()
        dataBinding?.glSurfaceView?.onResume()
    }

    override fun onPause() {
        dataBinding?.glSurfaceView?.onPause()
        renderer?.pause()
        super.onPause()
    }

    override fun onDestroyView() {
        renderer?.stop()
        renderer = null
        super.onDestroyView()
    }
}